package com.ruoyi.framework.security.filter

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.utils.SecurityUtils
import com.ruoyi.common.utils.StringUtils
import com.ruoyi.framework.security.service.TokenService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import java.io.IOException
import javax.servlet.FilterChain
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
class JwtAuthenticationTokenFilter : OncePerRequestFilter() {
    @Autowired
    private val tokenService: TokenService? = null

    @Throws(ServletException::class, IOException::class)
    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        val loginUser = tokenService!!.getLoginUser(request)

        loginUser?.let {
            SecurityUtils.getAuthentication() ?: run {
                tokenService!!.verifyToken(loginUser)
                val authenticationToken = UsernamePasswordAuthenticationToken(loginUser, null, loginUser.authorities)
                authenticationToken.details = WebAuthenticationDetailsSource().buildDetails(request)
                SecurityContextHolder.getContext().authentication = authenticationToken
            }
        }
//        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
//            tokenService.verifyToken(loginUser!!)
//            val authenticationToken = UsernamePasswordAuthenticationToken(loginUser, null, loginUser.authorities)
//            authenticationToken.details = WebAuthenticationDetailsSource().buildDetails(request)
//            SecurityContextHolder.getContext().authentication = authenticationToken
//        }
        chain.doFilter(request, response)
    }
}
